<template>
  <!-- 购物车 -->
  <div class="cart" style="padding-bottom: 110px">
    <van-nav-bar
      title="购物车"
      left-text="返回"
      :right-text="editing ? '完成' : '编辑'"
      @click-right="editing = !editing"
      left-arrow
    ></van-nav-bar>

    <!-- 购物车为空时显示 -->
    <van-empty v-show="cartList.length === 0" class="bg-fff h100pc">
      <template #description>
        <div v-if="token">
          <span>购物车空空如也</span>
          <router-link to="/" class="base ml-5">回首页</router-link>
        </div>
        <div v-else>
          <span>您还没登录,</span>
          <router-link to="/login" class="base ml-5">去登录</router-link>
        </div>
      </template>
    </van-empty>

    <!-- 列表 -->
    <van-checkbox-group v-model="result">
      <li class="flx-cent" v-for="item in cartList" :key="item.cartId">
        <van-checkbox
          :name="item.cartId"
          checked-color="#C03131"
          icon-size="15px"
        ></van-checkbox>
        <div class="fg1 flex">
          <div class="cart-goods">
            <img :src="item.imgUrl" alt />
          </div>
          <div class="cart-container flex2 jc-sb h100pc">
            <p class="goods-msg">{{ item.masterName }}</p>
            <div class="flex jc-sb aic" style="height: 28px">
              <span class="price">￥ {{ item.price | fMoney }} </span>
              <!-- 步进器 -->
              <van-stepper
                v-if="editing"
                :value="item.buyNum"
                async-change
                @plus="changeBuyNum(item, 1)"
                @minus="changeBuyNum(item, -1)"
              />
              <span v-else class="f999 f12">x {{ item.buyNum }} </span>
            </div>
          </div>
        </div>
      </li>
    </van-checkbox-group>

    <!-- 底部 -->
    <van-submit-bar
      :price="totalMoney"
      @submit="submit"
      :button-text="editing ? '删除' : '结算'"
    >
      <van-checkbox icon-size="15px" :value="result2" @click="selectAll"
        >全选</van-checkbox
      >
    </van-submit-bar>

    <Footer></Footer>
  </div>
</template>

<script>
import Footer from "@/components/Footer";
import $http from "@/utils/http";
export default {
  components: {
    Footer,
  },

  data() {
    return {
      // 选中的checkbox数组
      result: [],
      // 全选
      result2: false,
      // 定义编辑状态
      editing: false,
      // 购物车列表数组
      cartList: [],
    };
  },
  
  created() {
    console.log("---created---");
    this.getList();
  },

  mounted() {
    console.log("---mounted---");
  },

  deactivated() {
    console.log("---deactivated---");
  },
  activated() {
    console.log("---activated---");
  },

  watch: {
    // 监听result的变化, 然后进行操作
    result(newV, oldV) {
      // 选中的商品数组长度和所有商品数组长度相等时,为全选
      if (this.result.length === this.cartList.length) {
        this.result2 = true;
      } else {
        this.result2 = false;
      }
    },
  },

  computed: {
    token() {
      return this.$store.state.token;
    },
    // 根据this.result计算总价
    totalMoney() {
      // list:选出被选中的商品
      let list = this.cartList.filter((cart) => {
        return this.result.includes(cart.cartId);
      });

      let sum = 0;
      list.forEach((item) => {
        // 每个商品的单价*数量
        let price = item.price * item.buyNum;
        sum += price;
      });
      return sum;
    },
  },

  methods: {
    // 提交
    submit() {
      // editing为true,删除,否则结算
      if (this.editing) {
        let params = {
          cartId: this.result,
        };

        this.$dialog
          .confirm({
            title: "温馨提示",
            message: "确定删除吗?",
          })
          .then(() => {
            $http.post("/cart/del", params).then((res) => {
              // 成功之后,给cartList重新赋值,新数组为没被选中的商品
              let list = this.cartList.filter((cart) => {
                return !this.result.includes(cart.cartId);
              });
              this.cartList = list;
              this.$toast.success("删除成功");
            });
          });
      } else {
        let params = {
          totalMoney: this.totalMoney,
          cartId: this.result,
        };
        console.log(params);
        $http.post("/preOrder/create", params).then((res) => {
          this.$router.push({
            path: "/order/verify",
            query: {
              preOrderId: res.result.preOrderId,
            },
          });
        });
      }
    },
    // 全选
    selectAll() {
      this.result2 = !this.result2;
      // 为true说明是全选,否则为全不选
      if (this.result2) {
        // 把所有商品的cartId放入result数组即可
        this.result = this.cartList.map((item) => item.cartId);
      } else {
        this.result = [];
      }
    },
    // 修改购买数量
    changeBuyNum(item, num) {
      let buyNum = item.buyNum + num;
      let params = {
        buyNum,
        cartId: item.cartId,
      };
      $http.post("/cart/updateNum", params).then((res) => {
        item.buyNum = buyNum;
      });
    },
    getList() {
      this.loadingStart();
      $http.get("/cart/all").then((res) => {
        this.cartList = res.list;
        this.loadingEnd();
      });
    },
  },
};
</script>

<style lang="less">
@import "./index.less";
.cart {
  .van-submit-bar {
    bottom: 50px;
  }
}
</style>